﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

using KEW.InterFace;

namespace AutoGam
{
    public partial class PurchForm : Form
    {
        private const int QtyLength = 3;
        private const int NumberLen = 5;
        private const int CarLength = 7;
        public string CardSerial = "";
        public string CardNo = "";
        public string BaseName = "";

        String[] SupplyName;
        String uid = Guid.NewGuid().ToString();
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        public PurchForm()
        {
            InitializeComponent();
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲

            if (!Program.IsDebug)
            {
                this.TopMost = true;
                this.WindowState = FormWindowState.Maximized;
            }
        }



        private void PageSales_NumClear_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            PageSales_NumText.Text = String.Empty;
        }

        private void PageSales_NumDelete_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            if (PageSales_NumText.Text.Length > 0)
            {
                PageSales_NumText.Text = PageSales_NumText.Text.Substring(0, PageSales_NumText.Text.Length - 1);
            }
        }

        private void PageSales_Num_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            if (PageSales_NumText.Text.Length < NumberLen)
            {
                PageSales_NumText.Text += ((Button)sender).Text;
            }
        }

        private void PageSales_NumNext_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            if (PageSales_NumText.Text.Length >= NumberLen)
            {
                Boolean isPass = false;
                
                String baseKey = PageSales_NumText.Text.Substring(0, 1);
                String orderNo = PageSales_NumText.Text.Substring(1, 4);
                if (Program.DataConnString.ContainsKey(baseKey))
                {
                    DataSet data = new DataSet();
                    OleDbConnection conn = new OleDbConnection();
                    conn.ConnectionString = Program.DataConnString[baseKey];

                    String sql = String.Format("SELECT FBillNo BillNo,FText CarNumber,FTime BuildTime FROM KEW_PurchInfo WHERE FID IN (SELECT Distinct(A.FID) From KEW_PurchInfo A LEFT JOIN KEW_PurchInfoEntry B ON A.FID=B.FID WHERE A.FComboBox!='3' AND A.FCheckBox4=0 AND B.FBillNo_SRC='{0}') ORDER BY FTime\r\n", orderNo);
                    sql += String.Format("SELECT A.FID,Isnull(B.FID,0) ItemID,Isnull(B.FName,0) ItemName,Isnull(B.FNumber,'') ItemNumber,A.FNOTE,Isnull(B.FName,'') ItemName,C.FName GName FROM KEW_PurchOrderQty A LEFT JOIN KEW_PurchItemEntry B ON A.FBase4=B.FID LEFT JOIN t_Supplier C ON A.FBase=C.FItemID WHERE A.FBillNo='{0}' AND A.FCheckBox=0 AND A.FUser>0\r\n", orderNo);
                    sql += String.Format("SELECT FValue FROM t_systemprofile WHERE fcategory='general' and fkey='CompanyName'");
                    OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
                    try
                    {
                        PageSales_NumMessage.Text = "正在查询，请稍候...";
                        Application.DoEvents();
                        adapter.Fill(data);
                        String companyName = data.Tables[2].Rows[0]["FValue"].ToString();
                        companyName = companyName.Substring(0, companyName.Length > 8 ? 8 : companyName.Length);
                        if (BaseName != "" && BaseName != companyName)
                        {
                            PageSales_NumMessage.Text = String.Format("该磁卡不是本厂发出，请检查。");
                        }
                        else if (data.Tables[0].Rows.Count > 30)
                        {
                            PageSales_NumMessage.Text = String.Format("同一个订单下已经存在{0}车,不能继续办理，请等待其他车辆出厂或者转人工办理。", data.Tables[0].Rows.Count);
                        }
                        else if (data.Tables[1].Rows.Count == 1)
                        {
                            isPass = true;
                            DataRow row = data.Tables[1].Rows[0];
                            OrderID = row["FID"].ToString();
                            PageConfirmItem.Text = row["ItemName"].ToString();
                            //Note = row["FNote"].ToString();
                            //PageCar_Text.Text = row["CarNo"].ToString().Trim();
                            //PageCar_Panel.Enabled = (PageCar_Text.Text == "");
                            PurchTab.SelectedTab = TabPageInuputCarNo;

                            SupplyName = Com.Split(row["GName"].ToString());
                        }
                        else
                        {
                            PageSales_NumMessage.Text = "错误的编号(同时有可能是订单尚未审核，请检查确认)";
                            Device.Voice("编号不正确.wav");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    conn.Dispose();
                }
                else
                {
                    PageSales_NumMessage.Text = "错误的编号。";
                    Device.Voice("编号不正确.wav");
                }
            }
            else
            {
                PageSales_NumMessage.Text = String.Format("您输入的编号长度不是{0}位。", NumberLen);
                Device.Voice("编号不正确.wav");
            }
        }

        private void PageCar_Next_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            if (PageCar_Text.Text != String.Empty)
            {
                PurchTab.SelectedTab = TabPageSalesConfirm;
            }
        }

        private void PageConfirm_Next_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            PageConfirm_Message.Text = "请稍候，正在为您办理！";
            PageConfirm_Next.Text = "请 稍 候";
            Device.Voice("voice1.wav");
            PageConfirm_Next.Enabled = false;
            String cardNo = "";
            String cardId = "";
            String baseId = "";

            Application.DoEvents();

            DataSet data = new DataSet();
            DataSet carddata = new DataSet();
            DataSet cardata = new DataSet();
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = Program.DataConnString[PageSales_NumText.Text.Substring(0, 1)];

            try
            {
                OleDbDataAdapter carOle = new OleDbDataAdapter(String.Format("SELECT 1 FROM KEW_PurchInfo WHERE FText='{0}' AND FComboBox IN ('0','1','2') AND FCheckBox4=0", PageCar_Text.Text), conn);
                carOle.Fill(cardata);
                if (cardata.Tables[0].Rows.Count > 0)
                {
                    PageConfirm_Message.Text = "车辆" + PageCar_Text.Text + "尚未出厂，不能重复开卡。";
                    PageConfirm_Next.Text = "";
                    PageConfirm_Next.Enabled = true;
                }
                else
                {
                    String serial = Device.GetCardAndReturnSerial(); ;
                    if (serial == String.Empty)
                    {
                        PageConfirm_Message.Text = "磁卡用光了，请联系管理人员！";
                        PageConfirm_Next.Enabled = true;
                        PageConfirm_Next.Text = "确    定";
                    }
                    else
                    {
                        int tryTimes = 0;
                        int canTimes = 5;
                        OleDbDataAdapter cardOle = new OleDbDataAdapter(String.Format("SELECT FID,FNumber FROM CardServer.DBO.KEW_ICCardEntry WHERE FText='{0}' SELECT FID FROM CardServer.DBO.KEW_DataBaseEntry WHERE FText=DB_NAME() SELECT 1 FROM KEW_PurchInfo WHERE FText='{1}' AND FComboBox!='3' AND FCheckBox4=0", serial, PageCar_Text.Text), conn);
                        try
                        {
                            cardOle.Fill(carddata);

                            if (carddata.Tables[0].Rows.Count == 0)
                            {
                                PageConfirm_Message.Text = "磁卡尚未注册，请联系管理员";
                                PageConfirm_Next.Text = "重    试";
                                PageConfirm_Next.Enabled = true;
                            }
                            else if (carddata.Tables[1].Rows.Count != 1)
                            {
                                PageConfirm_Message.Text = "账套尚未注册，请联系管理员";
                                PageConfirm_Next.Text = "重    试";
                                PageConfirm_Next.Enabled = true;
                            }
                            else
                            {
                                cardId = carddata.Tables[0].Rows[0]["FID"].ToString();
                                cardNo = carddata.Tables[0].Rows[0]["FNumber"].ToString();
                                baseId = carddata.Tables[1].Rows[0]["FID"].ToString();

                                //while (tryTimes < canTimes)
                                //{
                                //    if (Device.UsbCardDevice.WriteBlock(SupplyName[0], Block.Block04) &&
                                //    Device.UsbCardDevice.WriteBlock(SupplyName[1], Block.Block05) &&
                                //    Device.UsbCardDevice.WriteBlock(SupplyName[2], Block.Block06) &&
                                //    Device.UsbCardDevice.WriteBlock(PageConfirmItem.Text, Block.Block08) &&
                                //    Device.UsbCardDevice.WriteBlock(PageConfirmCar.Text, Block.Block09) &&
                                //    Device.UsbCardDevice.WriteBlock("", Block.Block10) &&  //备注
                                //    Device.UsbCardDevice.WriteBlock("", Block.Block12) && //收发人
                                //    Device.UsbCardDevice.WriteBlock("0", Block.Block13) &&
                                //    Device.UsbCardDevice.WriteBlock("正常", Block.Block14) &&
                                //    Device.UsbCardDevice.WriteBlock("采购.已开票", Block.Block16) &&
                                //    Device.UsbCardDevice.WriteBlock("", Block.Block17) && //销售批次编号
                                //    Device.UsbCardDevice.WriteBlock("", Block.Block18)) //生产线
                                //    {
                                //        break;
                                //    }
                                //    else
                                //    {
                                //        tryTimes++;
                                //    }
                                //}

                                if (tryTimes < canTimes)
                                {

                                    StringBuilder sql = new StringBuilder();
                                    sql.Append("SET NOCOUNT ON\r\n");
                                    sql.Append("DECLARE @FID INT\r\n DECLARE @BillNo NVARCHAR(50) \r\n");
                                    sql.Append("EXEC KEW_GET_BillNo 236900124,1,@BillNo OUTPUT \r\n  EXEC GetICMaxNum 'KEW_PurchInfo',@FID OUTPUT \r\n");
                                    sql.Append("INSERT INTO KEW_PurchInfo ([FID],[FClassTypeID],[FBillNo],[FAmount],[FAmount1],[FAmount2],[FComboBox],[FText],[FDecimal],[FDecimal18]");
                                    sql.Append(",[FDecimal1],[FDecimal2],[FDecimal3],[FDecimal4],[FTime],[FTime1],[FTime2],[FText1],[FText2],[FText3],[FBase],[FNOTE]");
                                    sql.Append(",[FCheckBox],[FBase1],[FBase2],[FText4],[FText8],[FText5],[FNOTE2],[FCheckBox4],[FComboBox2],[FText11],[FInteger1],[FText14]) \r\n");
                                    sql.AppendFormat("SELECT @FID,236900124,@BillNo,0,0,0,'1','{0}',0,0,  0,0,0,0,GETDATE(),Null,Null,'自助开票','','',A.FBase4,'',   0,A.FBase,B.FBase3,'','{1}','{2}','',0,'0',A.FBillNo,A.FID,'{3}({4})' \r\n", PageCar_Text.Text, cardNo, uid, CardSerial, CardNo);
                                    sql.AppendFormat("FROM KEW_PurchOrderQty A LEFT JOIN KEW_PurchItemEntry B ON A.FBase4=B.FID WHERE A.FID={0}\r\n", OrderID);

                                    sql.Append("INSERT INTO KEW_PurchInfoEntry ([FID],[FIndex],[FBillNo_SRC],[FClassID_SRC],[FComboBox1],[FDecimal11],[FDecimal5],[FDecimal6]");
                                    sql.Append(",[FDecimal7],[FDecimal8],[FDecimal9],[FDecimal10],[FID_SRC],[FEntryID_SRC],[FCheckBox2],[FBase4],[FText6],[FText7],[FInteger])\r\n");
                                    sql.AppendFormat("SELECT @FID,1,A.FBillNo,236900121,1,A.FDecimal,A.FDecimal11,A.FDecimal9-A.FDecimal12,   A.FDecimal3,0,0,0,A.FID,0,0,A.FBase,'{0}','',0\r\n", uid);
                                    sql.AppendFormat("FROM KEW_PurchOrderQty A WHERE A.FID={0} \r\n", OrderID);
                                    sql.AppendFormat("UPDATE CardServer.DBO.KEW_ICCardEntry SET FComboBox='1',FCheckBox1=1,FCheckBox=0,FCheckBox2=1,FText1='',FText2=@FID,FBase={0} WHERE FID={1}\r\n", baseId, cardId);
                                    sql.AppendFormat("SELECT FID FROM KEW_PurchInfo WHERE FText5='{0}' \r\n", uid);

                                    sql.Append("SET NOCOUNT OFF");

                                    OleDbDataAdapter adapter = new OleDbDataAdapter(sql.ToString(), conn);

                                    try
                                    {
                                        adapter.Fill(data);

                                        if (data.Tables[0].Rows.Count == 1)
                                        {
                                            Device.SendCard();
                                            PageConfirm_Message.Text = "办理完毕,请您拿好磁卡,5秒后将自动关闭界面。";
                                            PageConfirm_Next.Text = "欢迎再次使用";
                                            PageConfirm_Next.Visible = false;
                                            PageConfirm_Return.Text = "关闭";
                                            Device.Voice("voice8.wav");
                                            Device.CountDown = 5;
                                        }
                                        else
                                        {
                                            PageConfirm_Message.Text = "执行错误,请重试";
                                            PageConfirm_Next.Enabled = true;
                                            PageConfirm_Next.Text = "确    定";
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        PageConfirm_Message.Text = "数据访问错误：" + ex.Message;
                                        PageConfirm_Next.Enabled = true;
                                    }
                                }
                                else
                                {
                                    Device.ReviceCard();
                                    PageConfirm_Message.Text = "出现错误，请重新尝试。";
                                    PageConfirm_Next.Text = "重    试";
                                    PageConfirm_Next.Enabled = true;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            PageConfirm_Message.Text = "数据访问错误：" + ex.Message;
                            PageConfirm_Next.Enabled = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PageConfirm_Message.Text = "错误：" + ex.Message;
                PageConfirm_Next.Enabled = true;
            }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Application.DoEvents();
            if (PageSales_NumText.Text == "")
            {
                //Device.Voice("voice7.wav");
            }
        }

        private void ButtonCarNoCHS_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            String value = ((Button)sender).Text;
            if (PageCar_Text.Text.Length == 0)
            {
                PageCar_Text.Text = value;
            }
            else
            {
                if (System.Text.Encoding.GetEncoding("GBK").GetBytes(PageCar_Text.Text.Substring(0, 1)).Length != 1)
                {
                    PageCar_Text.Text = value + PageCar_Text.Text.Substring(1, PageCar_Text.Text.Length - 1);
                }
                else
                {
                    PageCar_Text.Text = value + PageCar_Text.Text;
                }
            }
        }

        private void ButtonCarNoChar_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            if (PageCar_Text.Text.Length < CarLength)
            {
                String value = ((Button)sender).Text;
                PageCar_Text.Text += value;
            }
        }

        private void PageCar_Clear_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            PageCar_Text.Text = String.Empty;
        }

        private void PageCar_Delete_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            if (PageCar_Text.Text.Length > 0)
            {
                PageCar_Text.Text = PageCar_Text.Text.Substring(0, PageCar_Text.Text.Length - 1);
            }
        }

        private void MainTab_Selecting(object sender, TabControlCancelEventArgs e)
        {
            if (e.TabPageIndex == 0 && OrderID != String.Empty)
            {
                e.Cancel = true;
                return;
            }
            if (e.TabPageIndex != 0 && OrderID == String.Empty)
            {
                e.Cancel = true;
                return;
            }
            switch (e.TabPageIndex)
            {
                case 0:
                    //Device.Voice("voice7.wav");
                    PageSales_NumMessage.Text = "请输入您的供货编号。";
                    break;
                case 1:
                    if (PageCar_Panel.Enabled)
                    {
                        if (PageCar_Text.Text == "")
                        {
                            PageCar_Message.Text = "请输入您的车牌号。";
                            Device.Voice("voice2.wav");
                        }
                        else
                        {
                            PageCar_Message.Text = "请确认信息";
                            Device.Voice("voice6.wav");
                        }
                    }
                    else
                    {
                        PageCar_Message.Text = "车牌号不能修改，请直接点击下一步选择产品及数量";
                    }
                    break;
                case 2:
                    if (PageCar_Text.Text == String.Empty)
                    {
                        e.Cancel = true;
                        return;
                    }
                    Device.Voice("voice6.wav");
                    PageConfirmCar.Text = PageCar_Text.Text;
                    break;
            }
        }

        private void ButtonCancel_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            Exit();
        }

        private void Exit()
        {
            this.Close();
        }

        private void Clear()
        {
            PageSales_NumText.Text = String.Empty;
            PageCar_Text.Text = String.Empty;
            PurchTab.SelectedTab = TabPageInputBillNo;
        }

        private void PageConfirm_Return_Click(object sender, EventArgs e)
        {
            Device.ButtonVoice();
            if (PageConfirm_Return.Text == "关闭")
            {
                this.Close();
            }
            else
            {
                PurchTab.SelectedTab = TabPageInuputCarNo;
            }
        }

        private void MainForm_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Back:
                    Exit();
                    break;
                case Keys.Escape:
                    Exit();
                    break;
            }
        }

        private void SalesForm_SizeChanged(object sender, EventArgs e)
        {
            PurchTab.Size = this.Size;
        }

        private void MainTimer_Tick(object sender, EventArgs e)
        {
            if (Device.CountDown > 0)
            {
                Device.CountDown--;
            }
            else if (Device.CountDown == 0)
            {
                this.Close();
            }
            //if (PageSales_NumText.Text == "")
            //{
            //    try
            //    {
            //        String currSerial = Device.ComCardDevice.GetSerial();
            //        if (currSerial != "")
            //        {
            //            if (UseSerial == "")
            //            {
            //                UseSerial = currSerial;
            //                if (Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block32) == "采购供货")
            //                {
            //                    PageSales_NumText.Text = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block33); //编号
            //                    PageCar_Text.Text = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block36); //车牌号
            //                    CardSerial = UseSerial;
            //                    CardNo = Device.ComCardDevice.ReadBlock(KEW.InterFace.Block.Block34); //磁卡编号
            //                    PageSales_NumNext_Click(null, null);
            //                }
            //            }
            //        }
            //        else
            //        {
            //            UseSerial = "";
            //        }
            //    }
            //    catch (Exception) { }
            //}
        }
        private string UseSerial = "";


        private List<AccountTemp> AccountList = new List<AccountTemp>();

        private String OrderID = String.Empty;
        private String Gust = String.Empty;
        private String Note = String.Empty;

        

        private void PageSales_ItemList_SelectedIndexChanged(object sender, EventArgs e)
        {
            Device.ButtonVoice();
        }
    }
}
